package com.itheima.service.Impl;

import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.dto.OrderSettingDto;
import com.itheima.pojo.vo.OrderSettingVO;
import com.itheima.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.CellType;
@Slf4j
@Service
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingMapper orderSettingMapper;

    /**
     * 下载文件
     * @param response
     * @param fileName
     */
    /*@Override
    public void download(HttpServletResponse response, String fileName) throws IOException {
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/ordersetting_template.xlsx");
        log.info("templates/" + fileName);
        XSSFWorkbook workbook = new XSSFWorkbook(in);

        for (int i = 0; i < 30; i++) {
            LocalDate localDate = beginTime.plusDays(i);
            OrderSetting orderSetting = orderSettingMapper.getOrderSettingByDate(localDate);
            XSSFSheet sheet = workbook.getSheetAt(0);
            if(orderSetting != null){

                XSSFRow row = sheet.getRow(i + 1);
                if (row == null) {
                    row = sheet.createRow(i + 1); // 如果行不存在则创建新行
                    row.createCell(0).setCellValue(orderSetting.getOrderDate().toString());
                    row.createCell(1).setCellValue(orderSetting.getNumber());
                }else {
                    row.createCell(0).setCellValue(orderSetting.getOrderDate().toString());
                    row.createCell(1).setCellValue(orderSetting.getNumber());
                }

            }else {
                 orderSetting = new OrderSetting(null,localDate,0,0);
                XSSFRow row = sheet.getRow(i + 1);
                if (row == null) {
                    row = sheet.createRow(i + 1); // 如果行不存在则创建新行
                    row.createCell(0).setCellValue(orderSetting.getOrderDate().toString());
                    row.createCell(1).setCellValue(orderSetting.getNumber());

                    XSSFCell cell = sheet.getRow(i + 1).getCell(0);
                    XSSFCell cell2 = sheet.getRow(i + 1).getCell(1);
                    System.out.println(cell+" "+cell2);

                }else {
                    row.createCell(0).setCellValue(orderSetting.getOrderDate().toString());
                    row.createCell(1).setCellValue(orderSetting.getNumber());

                    XSSFCell cell = sheet.getRow(i + 1).getCell(0);
                    XSSFCell cell2 = sheet.getRow(i + 1).getCell(1);
                    System.out.println(cell+" "+cell2);

                }  }
        }
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);

        out.close();
        workbook.close();
    }*/

    /**
     * 下载模板
     * @param response
     * @param fileName
     * @throws IOException
     */
    @Override
    public void download(HttpServletResponse response, String fileName) throws IOException {
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/ordersetting_template.xlsx");
        log.info("templates/" + fileName);
        XSSFWorkbook workbook = new XSSFWorkbook(in);

        for (int i = 0; i < 30; i++) {
            LocalDate localDate = beginTime.plusDays(i);
            OrderSetting orderSetting = orderSettingMapper.getOrderSettingByDate(localDate);
            XSSFSheet sheet = workbook.getSheetAt(0);
            if(orderSetting != null){

                XSSFRow row = sheet.getRow(i + 1);
                if (row == null) {
                    row = sheet.createRow(i + 1); // 如果行不存在则创建新行
                    row.createCell(0).setCellValue(orderSetting.getOrderDate().toString());
                    row.createCell(1).setCellValue(orderSetting.getNumber());
                }else {
                    row.createCell(0).setCellValue(orderSetting.getOrderDate().toString());
                    row.createCell(1).setCellValue(orderSetting.getNumber());
                }

            }else {
                orderSetting = new OrderSetting(null,localDate,0,0);
                XSSFRow row = sheet.getRow(i + 1);
                if (row == null) {
                    row = sheet.createRow(i + 1); // 如果行不存在则创建新行
                    row.createCell(0).setCellValue(orderSetting.getOrderDate().toString());
                    row.createCell(1).setCellValue(orderSetting.getNumber());

                    XSSFCell cell = sheet.getRow(i + 1).getCell(0);
                    XSSFCell cell2 = sheet.getRow(i + 1).getCell(1);
                    System.out.println(cell+" "+cell2);

                }else {
                    row.createCell(0).setCellValue(orderSetting.getOrderDate().toString());
                    row.createCell(1).setCellValue(orderSetting.getNumber());

                    XSSFCell cell = sheet.getRow(i + 1).getCell(0);
                    XSSFCell cell2 = sheet.getRow(i + 1).getCell(1);
                    System.out.println(cell+" "+cell2);

                }  }
        }
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);

        out.close();
        workbook.close();
    }
    /**
     * 获取预约设置数据
     * @param
     * @return
     */
    @Override
    public List<OrderSettingVO> getOrderSettingByMonth(String month) {

        //将date 转换成Date
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M");
        // 先解析成 YearMonth
        YearMonth yearMonth = YearMonth.parse(month, formatter);

        // 获取当月的第一天
        LocalDate beginDate = yearMonth.atDay(1);
        // 获取当月最后一天
        LocalDate endDate = yearMonth.atEndOfMonth();

        List<OrderSettingVO> list = new ArrayList<>();
        while (!beginDate.equals(endDate)){
            OrderSetting orderSetting = orderSettingMapper.getOrderSettingByDate(beginDate);
            if(orderSetting == null) {
                int dayOfMonth = beginDate.getDayOfMonth();

                OrderSettingVO orderSettingVO = new OrderSettingVO(dayOfMonth,50,0);
                list.add(orderSettingVO);

            }else {
                OrderSettingVO orderSettingVO = new OrderSettingVO();
                int dayOfMonth = beginDate.getDayOfMonth();
                orderSettingVO.setDate(dayOfMonth);
                orderSettingVO.setNumber(orderSetting.getNumber());
                orderSettingVO.setReservations(orderSetting.getReservations());
                list.add(orderSettingVO);

            }

            beginDate = beginDate.plusDays(1);
        }

        return list;
    }

    /**
     * 编辑预约设置
     * @param orderSetting
     */
    @Override
    public void editNumberByOrderDate(OrderSettingDto orderSetting) {
        orderSettingMapper.editNumberByOrderDate(orderSetting);
    }

    /**
     * 上传文件
     * @param excelFile
     * @return
     */
    @Override
    public void upload(MultipartFile excelFile) {

            log.info( "文件路径"+String.valueOf(excelFile));
            if (excelFile == null){
                throw new RuntimeException("上传文件不能为空");
            }
        InputStream in = null;
        try {
            in = excelFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        XSSFSheet sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 1; i <= lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                Cell dateCell = row.getCell(0);
                LocalDate orderDate = null;

                if (dateCell != null) {
                    if (DateUtil.isCellDateFormatted(dateCell)) {
                        orderDate = dateCell.getDateCellValue().toInstant()
                                .atZone(java.time.ZoneId.systemDefault())
                                .toLocalDate();
                    } /*else {
                        switch (dateCell.getCellType()) {
                            case NUMERIC:
                                orderDate = DateUtil.getJavaDate(dateCell.getNumericCellValue()).toInstant()
                                        .atZone(java.time.ZoneId.systemDefault())
                                        .toLocalDate();
                                break;
                            case STRING:
                                orderDate = LocalDate.parse(dateCell.getStringCellValue());
                                break;
                        }
                    }*/
                }

                int number = (int) row.getCell(1).getNumericCellValue();

                OrderSetting orderSetting = new OrderSetting();
                orderSetting.setNumber(number);
                orderSetting.setOrderDate(orderDate);
                orderSetting.setReservations(0);
                orderSettingMapper.add(orderSetting);
            }

    }


}
